<?php

namespace App\Listeners;

use App\Events\OrderCompletedEvent;
use App\Models\DistributorUser;
use App\Models\IncomeDetails;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Distributor implements ShouldQueue
{
    /**
     * 任务被处理的延迟时间（秒）。
     *
     * @var int
     */
    public $delay = 5;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\OrderCompletedEvent  $event
     * @return void|bool
     */
    public function handle(OrderCompletedEvent $event)
    {
        $orderInfo = $event->orderInfo;
        Log::info('触发Distributor监听器 -> 订单ID：' . $orderInfo->order_nu);

        // 分销收益
        $user_id = $orderInfo->user_id;
        $invite_userid = User::where('id', $user_id)->value('invite_userid');
        if (empty($invite_userid)) {
            return false;
        }

        $distributorUser = DistributorUser::where('user_id', $invite_userid)->first();
        $income = bcmul($orderInfo->amount, bcdiv($distributorUser->income_ratio, '100', 2), 2);
        if (!empty($income)) {
            $exist = IncomeDetails::where('user_id', $invite_userid)->where('order_id', $orderInfo->id)->first();
            if (!empty($exist)) {
                return false;
            }

            $data = [
                'user_id' => $invite_userid,
                'order_id' => $orderInfo->id,
                'order_amount' => $orderInfo->amount,
                'income_ratio' => $distributorUser->income_ratio,
                'income' => $income
            ];
            if (IncomeDetails::create($data)) {
                $res = User::where('id', $invite_userid)->update([
                    'total_income' => DB::raw('total_income + ' . $income),
                    'income' => DB::raw('income + ' . $income)
                ]);
                if (empty($res)) {
                    Log::info('递增分销用户收益失败');
                    throw new \Exception('递增分销用户收益失败');
                }
            } else {
                Log::info('创建分销收益记录失败');
                throw new \Exception('创建分销收益记录失败');
            }
        }

        Log::info('Distributor监听器执行完毕 --> 订单ID：' . $orderInfo->order_nu);
    }
}
